#!/usr/bin/env python2.7
#-*- coding=utf-8 -*-

from ..cstructures import BigendCStruct
from .base import NetworkData

class TCP(NetworkData):
    def __init__(self, data):
        super(TCP, self).__init__(data)
        self.hdrlen = (self.hdrlen >> 4) * 0x4
        self.flag = self.flag & 0x3f
        if self.hdrlen > 20:
            optlen = self.hdrlen - 20
            self.optdata = self.restdata[:optlen]
            if len(self.optdata) < optlen:
                raise BufferError('Data buffer is not long enough!')
            self.restdata = self.restdata[optlen:]
            self.datalen += optlen

    def getnames(self):
        names = super(TCP, self).getnames()
        names.append('optdata')
        return names

    def verify(self):
        pass

    _fields_ = [
            ('srcport', 'WORD'),
            ('dstport', 'WORD'),
            ('seqnum', 'DWORD'),
            ('acknum', 'DWORD'),
            ('hdrlen', 'uByte'),
            ('flag', 'uByte'),
            ('window', 'WORD'),
            ('checksum', 'WORD'),
            ('urgent', 'WORD')
        ]

class UDP(NetworkData):
    def verify(self):
        pass

    _fields_ = [
            ('srcport', 'WORD'),
            ('dstport', 'WORD'),
            ('length', 'WORD'),
            ('checksum', 'WORD')
        ]

class ICMP(NetworkData):
    pass

layerdict = {
        6:TCP,
        17:UDP
    }
